# 导入相应的库
from tensorflow import keras
from tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import tensorflow as tf
from PIL import Image
import numpy as np
import itertools
import json
import os

# 设置图片的高和宽
im_height = 224
im_width = 224

#设置一次训练样本数和迭代次数
batch_size = 64    #一次训练所选取的样本数
epochs = 50   #训练时，使用所有数据集对模型进行一次完整的训练，称为一次epoch

image_path = "../datasets/"  # 猫狗数据集路径
train_dir = "../datasets/train"  # 训练集路径
validation_dir = "../datasets/test"  # 验证集路径

# 定义验证集图像生成器，并对图像进行预处理
validation_image_generator = ImageDataGenerator(rescale=1./255) # 归一化

# 使用图像生成器从验证集validation_dir中读取样本
val_data_gen = validation_image_generator.flow_from_directory(directory=validation_dir,  # 从验证集路径读取图片
                                                              batch_size=batch_size,  # 一次训练所选取的样本数
                                                              shuffle=False,  # 不打乱标签
                                                              target_size=(im_height, im_width),  # 图片resize到224x224大小
                                                              class_mode='categorical')  # one-hot编码

# 验证集样本数 :5000
total_val = val_data_gen.n
# 猫和狗两种标签，存入到labels中
labels = ['cats', 'dogs']
model = keras.models.load_model('./save_weights/ResNet50_tf.h5', compile=False)

# 预测验证集数据整体准确率,显示进度条
y_pred = model.predict(val_data_gen, total_val // batch_size + 1,verbose=1)
y_test = val_data_gen.classes
y_test = np.reshape(y_test, (-1, 1))
#计算准确率
acc = keras.metrics.SparseCategoricalAccuracy()(y_test, y_pred )  # 计算准确率
print("准确率：",acc)

#转换为预测标签
y_pred_classes = np.argmax(y_pred, axis=1)

# 计算混淆矩阵
# confusion_mtx = confusion_matrix(y_true=y_test, y_pred=y_pred_classes)
# # 绘制混淆矩阵
# plot_confusion_matrix(confusion_mtx, normalize=True, target_names=labels)

#绘制错分样例图片
count = 8
y_pred = np.reshape(y_pred_classes, (-1, 1))

ins = y_test != y_pred
diff_index = np.where(ins == True)[0]
print('diff_index',diff_index)
plt.figure()
# x_test = validation_image_generator
it = iter(val_data_gen)
x_test,_ = next(val_data_gen)
for x in it:
    yy,_ = x
    x_test = np.concatenate((x_test,yy),axis=0)
for i in range(count): #只显示前8个
    j = diff_index[i]
    img = x_test[j]      # 设值28*28
    plt.subplot(2, 4, i+1, xticks=[], yticks=[])# 2*8子图显示
    plt.imshow(img)
    ii = y_test[j][0]
    jj = y_pred[j][0]
    plt.title(f'{labels[ii]}--> {labels[jj]}', fontproperties='SimHei')  # 显示标题   # 显示标题
    plt.subplots_adjust(wspace=0.1, hspace=0.2)# 调整子图间距
plt.show()

